import { AUTH_HEADER_TOKEN_KEY } from "@/common";
import useAuthStore from "@/stores/useAuthStore";
import axios from "axios";
import { ElNotification } from "element-plus";

// 创建axios实例
const request = axios.create({
    baseURL: import.meta.env.VITE_API_PREFIX,
    timeout: 10_000
})

// 请求拦截器
request.interceptors.request.use(request => {
    // 添加token
    request.headers[AUTH_HEADER_TOKEN_KEY] = useAuthStore().authInfo?.token
    return request;
}, error => {
    ElNotification({
        title: '请求异常',
        message: error,
        type: 'error',
        duration: 1500
    })
})

// 响应拦截器
request.interceptors.response.use(response => {
    const { data } = response

    let title = ''
    let message = data.msg

    if (data.status == 200) {
        if (typeof data.data === 'boolean') {
            if (data.data) {
                ElNotification({
                    title: "操作结果",
                    message: "操作成功",
                    type: "success",
                })
                return;
            } else {
                title = '操作结果'
                message = '操作失败'
            }
        } else if (typeof data.data === 'object') {
            // data.data.headers = response.headers
            return data.data
        } else {
            ElNotification({
                title: "操作结果",
                message: `未知结果-${data.data}`,
                type: "warning",
                duration: 1500
            })
            return data.data
        }
    } else {
        switch (data.status) {
            // 请求参数错误
            case 400:
                title = '请求参数错误'
                break
            // 登录过期或未授权
            case 401:
                // 清空登录信息，需重新登录
                localStorage.clear()
                title = '登录已过期，请重新登录'
                break
            // 无权访问
            case 403:
                title = '无权访问'
                break
            // 资源不存在
            case 404:
                title = '请求资源不存在'
                break
            // 服务器错误
            case 500:
                title = '服务器错误'
                break
            default:
                title = `未知错误: ${data.status}`
                break
        }
    }
    ElNotification({
        title,
        message,
        type: 'error',
        duration: 1500,
        // 需要在提示框关闭后跳转到登录页面
        ...((data.status === 401) ? { onClose: () => location.reload() } : {})
    })
    return Promise.reject(new Error(title))
}, (error) => {
    let title = ''
    if (error.code === "ECONNABORTED" || error.code === "Network Error" || error.message.includes("timeout")) {
        // axios内部错误
        title = '请求超时'
    } else {
        switch (error.response?.status) {
            // 请求参数错误
            case 400:
                title = '请求参数错误'
                break
            // 登录过期或未授权
            case 401:
                // 清空登录信息，需重新登录
                localStorage.clear()
                title = '登录已过期，请重新登录'
                break
            // 无权访问
            case 403:
                title = '无权访问'
                break
            // 资源不存在
            case 404:
                title = '请求资源不存在'
                break
            // 服务器错误
            case 500:
                title = '服务器错误'
                break
            default:
                title = `未知错误: ${error.response?.status}`
                break
        }
    }

    ElNotification({
        title,
        message: 'error',
        type: 'error',
        duration: 1500
    })

    return Promise.reject(error)
})

export default request